using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using inmolib_common;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.IO;

public class ShowImageSample : MonoBehaviour
{
    public RawImage showRawImage;

    private Texture2D showTexture;

    private bool is6DofStarted;

    void Start()
    {
        if(!ArPoseManager.instance.is6Dof)
        {
            gameObject.SetActive(false);
            return;
        }

        showTexture = new Texture2D(480, 640, TextureFormat.Alpha8, false);
        showRawImage.texture = showTexture;
        showRawImage.color = Color.white;

        //获取相机参数。
        WaitCallback.instance.WaitAction(2.0f,()=> {
            //intrinsicParameters是相机内参返回9位，f为焦距，c为主心
            //fx, 0, cx, 0, fy, cy ,0,  0, 1
            //distortionCoefficients是相机畸变参数返回5位，k1,k2,p1,p2,k3
            ArPoseManager.Air3CameraParams air3CameraParams = ArPoseManager.instance.GetAir3CameraParams();
            Debug.LogError("相机内参=" + string.Join(", ", air3CameraParams.intrinsicParameters) + 
                ",\r\n畸变参数=" + string.Join(", ", air3CameraParams.distortionCoefficients));
        });

        //勾选了is6Dof，在Start方法会自动调用Start6Dof
        is6DofStarted = true;
    }

    void Update()
    {
        //只有6dof的情况下才能获取摄像头图像数据
        if (ArPoseManager.instance.is6Dof && is6DofStarted)
        {
            //获取ImageData, image是480x640的灰度图数据，timestamp是图像时间戳
            ArPoseManager.ImageData imageData = ArPoseManager.instance.GetAir3ImageData();
            if(imageData.timestamp == 0 || imageData.image == null || imageData.image.Length == 0)
            {
                return;
            }

            //显示imageData灰度图
            showTexture.LoadRawTextureData(imageData.image);
            showTexture.Apply();

            //vio图像写入本地
            //SaveGrayByteArrayAsImage(imageData.image,480,640, imageData.timestamp + ".jpg");
        }
    }

    /// <summary>
    /// 手动开启6dof，锁定camera
    /// </summary>
    private void ManualStart6Dof()
    {
        if (ArPoseManager.instance.is6Dof)
        {
            //每次开启6dof不会保存上次的位姿，位姿会重置为identity
            is6DofStarted = ArPoseManager.instance.Start6Dof();
        }
    }

    /// <summary>
    /// 手动关闭6dof，释放camera
    /// </summary>
    private void ManualStop6Dof()
    {
        if (ArPoseManager.instance.is6Dof)
        {
            ArPoseManager.instance.Stop6Dof();
            is6DofStarted = false;
        }
    }

    public void SaveGrayByteArrayAsImage(byte[] grayData, int width, int height, string fileName)
    {
        if (grayData == null || grayData.Length != width * height)
        {
            Debug.LogError("灰度数据为空或尺寸不一致");
            return;
        }

        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        // 将灰度 byte[] 转为 RGB Color[]
        Color[] pixels = new Color[grayData.Length];
        for (int i = 0; i < grayData.Length; i++)
        {
            float gray = grayData[i] / 255f;
            pixels[i] = new Color(gray, gray, gray); // RGB 通道统一为灰度值
        }

        tex.SetPixels(pixels);
        tex.Apply();

        byte[] imageBytes;
        if (fileName.EndsWith(".jpg"))
            imageBytes = tex.EncodeToJPG(95);
        else
            imageBytes = tex.EncodeToPNG();

        string imagepath = Path.Combine(Application.persistentDataPath, "images");
        if(!Directory.Exists(imagepath))
        {
            Directory.CreateDirectory(imagepath);
        }
        string path = Path.Combine(imagepath, fileName);
        File.WriteAllBytes(path, imageBytes);
        Debug.Log("保存灰度图成功：" + path);
    }
}
